<?php
/**
 * Created by PhpStorm.
 * User: Jerry
 * Date: 2016/12/21
 * Time: 9:45
 */

namespace SDXApi\Service;

use SDXApi\Model\HomeTemplateStencilGoodsCategoryModel;
use SDXApi\Repositories\BuyNowGoodsRepository;
use SDXApi\Repositories\GoodsRepository;


/**
 * Class HomeTemplateService
 * @package SDXApi\Service
 */
class HomeTemplateService
{
	/**
	 * @var \Model|\Think\Model
	 */
	protected static $templateModel;

	/**
	 * @var \Model|\Think\Model
	 */
	protected static $templateStencilModel;

	/**
	 * @var \Model|\Think\Model
	 */
	protected static $templateStencilImageModel;

	/**
	 * @var \Model|\Think\Model
	 */
	protected static $goodsModel;

	/**
	 * @var \Model|\Think\Model
	 */
	protected static $templateStencilFontModel;

	/**
	 * @var
	 */
	protected $errorMessage;

	/**
	 * @var
	 */
	private $userId;

	/**
	 * @var
	 */
	private $wid;

	/**
	 * @var \Model|\Think\Model
	 */
	protected static $seminarModel;

	/**
	 * @var GoodsRepository
	 */
	protected static $goodsRepository;

	/**
	 * @var BuyNowGoodsRepository
	 */
	protected static $buyNowGoodsRepository;

	/**
	 * @var \Model|\Think\Model
	 */
	protected static $templateStencilGoodsModel;

	/**
	 * @var \Model|\Think\Model
	 */
	protected static $templateStencilSeminarModel;

	/**
	 * @var
	 */
	protected static $templateStencilGoodsCategoryModel;

	/**
	 * @var
	 */
	private $oldVersion;

	/**
	 * @var int
	 */
	public $isShow = 0;


	/**
	 * 注入实例
	 * HomeTemplateService constructor.
	 * @param $userId
	 * @param $wid
	 */
	public function __construct($userId, $wid)
	{
		self::$templateModel = D('HomeTemplate');

		self::$templateStencilModel = D('HomeTemplateStencil');

		self::$templateStencilGoodsModel = D('HomeTemplateStencilGoods');

		self::$templateStencilImageModel = D('HomeTemplateStencilImage');

		self::$templateStencilFontModel = D('HomeTemplateStencilFont');

		self::$seminarModel = D('Seminar');

		self::$templateStencilSeminarModel = D('HomeTemplateStencilSeminar');

		self::$goodsModel = D('Goods');

		self::$goodsRepository = new GoodsRepository($userId, $wid);

		self::$buyNowGoodsRepository = new BuyNowGoodsRepository($userId, $wid);

		self::$templateStencilGoodsCategoryModel = D('HomeTemplateStencilGoodsCategory');

		$this->userId = $userId;
		$this->wid = $wid;
	}

	/**
	 * Created by Jerry
	 * @param $name
	 * @param $value
	 * @return $this
	 */
	public function __set($name, $value)
	{
		$this->$name = $value;
		return $this;
	}


	/**
	 * Created by Jerry
	 * @param $id
	 * @return mixed
	 */
	protected function findTemplateById($id)
	{
		return self::$templateModel->find_home_template_for_status_by_id($id);
	}

	/**
	 * Created by Jerry
	 * @param $templateId
	 * @return mixed
	 */
	protected function findTemplateStencilByTemplateId($templateId)
	{
		return self::$templateStencilModel->find_template_stencil_by_template_id($templateId);
	}

	/**
	 * Created by Jerry
	 * @param $stencilId
	 * @return mixed
	 */
	protected function findTemplateStencilImageByStencilId($stencilId)
	{
		return self::$templateStencilImageModel->find_template_stencil_images_by_stencil_id($stencilId);
	}

	/**
	 * Created by Jerry
	 * @param $stencilId
	 * @return mixed
	 */
	protected function findTemplateStencilGoodsByStencilId($stencilId)
	{
		return self::$templateStencilGoodsModel->findHomeTemplateGoodsByTemplateId($stencilId, $this->wid);
	}

	/**
	 * Created by Jerry
	 * @param $stencilId
	 * @return mixed
	 */
	protected function findTemplateStencilFontByStencilId($stencilId)
	{
		return self::$templateStencilFontModel->find_template_stencil_font_by_stencil_id($stencilId);
	}

	/**
	 * Created by Jerry
	 * @param $stencilId
	 * @return mixed
	 */
	protected function findTemplateStencilSeminarByStencilId($stencilId)
	{
		$data = self::$templateStencilSeminarModel->find_seminars_by_stencil_id($stencilId);
		if (empty($data)) {
			$data = array();
		}

		return $data;
	}

	/**
	 * Created by Jerry
	 * @param $id
	 * @return mixed
	 */
	protected function findTemplateStencilSeminarForSeminarById($id)
	{
		return self::$seminarModel->find_seminar_template_by_id($id);
	}

	/**
	 * 获取当天所有秒杀商品
	 * Created by Jerry
	 * @param $startTime
	 * @param $endTime
	 * @return mixed
	 */
	protected function findGoodsBuyNowListByPromoteTime($startTime, $endTime)
	{
		return self::$goodsModel->findGoodsBuyNowListByPromoteTime($startTime, $endTime);
	}

	/**
	 * Created by Jerry
	 * @param $message
	 * @return $this
	 */
	protected function setErrorMessage($message)
	{
		array_push($this->errorMessage, $message);
		return $this;
	}

	/**
	 * Created by Jerry
	 * @param $groupId
	 * @return array|bool
	 */
	public function getHomeTemplateByGroup($groupId)
	{

		$group = $this->findHomeTemplateByGroup($groupId);
//		dd($group);
		if (empty($group)) {
			return false;
		}

		return $this->checkHomeTemplateGroupData($group);
	}

	/**
	 * 返回分组下启用模块的名称
	 * Created by Jerry
	 * @param $groupId
	 * @return bool|mixed
	 */
	public function getHomeTemplateGroupName($groupId)
	{
		$group = $this->findHomeTemplateByGroup($groupId);

		if (empty($group)) {
			return false;
		}

		$templateParent = $this->findHomeTemplateByParentId($group['id']);

		if (empty($templateParent) && $this->isShow) {
			return $group;
		}

		return $templateParent;
	}

	/**
	 * 获取指定分组信息
	 * Created by Jerry
	 * @param $groupId
	 * @return bool
	 */
	protected function findHomeTemplateByGroup($groupId)
	{
		if (empty($groupId)) {
			return false;
		}

		return self::$templateModel->find_home_template_by_group_id($groupId, $this->isShow);
	}

	/**
	 * 处理分组数据信息
	 * Created by Jerry
	 * @param $data
	 * @return array|bool
	 */
	protected function checkHomeTemplateGroupData($data)
	{
		if (empty($data)) {
			return false;
		}

		$templateData = $this->findHomeTemplateByParentId($data['id']);

		if (empty($templateData) && $this->isShow) {
			$stencil = $this->findTemplateStencilByTemplateId($data['id']);
		}
		else{
			$stencil = $this->findTemplateStencilByTemplateId($templateData['id']);
		}
		return $this->templateStencil($stencil);
	}

	/**
	 * 返回改组下启用的模块
	 * Created by Jerry
	 * @param $parentId
	 * @return mixed
	 */
	protected function findHomeTemplateByParentId($parentId)
	{
		return self::$templateModel->find_home_template_by_parent_id($parentId, $this->isShow);
	}


	/**
	 * Created by Jerry
	 * @param $id
	 * @return array
	 */
	public function getHomeTemplateStencil($id)
	{
		$template = $this->findTemplateById($id);

		if (empty($template)) {
			$this->setErrorMessage('暂无数据');
		}

		$stencil = $this->findTemplateStencilByTemplateId($template['id']);

		return $this->templateStencil($stencil);

	}

	/**
	 * Created by Jerry
	 * @param $stencils
	 * @return array
	 */
	protected function templateStencil($stencils)
	{
		if (empty($stencils)) {
			$this->setErrorMessage('暂无模块数据');
		}

		$data = array();
		foreach ($stencils as $key => $value) {
			$stencil = $this->stencilType($value);

			if (empty($stencil)) {
				continue;
			}

//			模块边距
			$stencil['border_size'] = 20;

			$data[] = $stencil;
		}

		return $data;
	}

	/**
	 * Created by Jerry
	 * @param $stencil
	 * @return array|mixed
	 */
	protected function stencilType($stencil)
	{
		$data = array();
		switch ($stencil['type']){
			case 1:
				$data = $this->fontType($stencil);
				break;
			case 2:
				$data = $this->imageType($stencil);
				break;
			case 3:
				$data = $this->speedType($stencil);
				break;
			case 4:
				$data = $this->goodsType($stencil);
				break;
			case 5:
				$data = $this->seminarType($stencil);
				break;
			case 6:
				$data = $this->buyNowType($stencil);
				break;
			case 7:
				$data = $this->recommend($stencil);
				break;
			case 8:
				$data = $this->categoryGoods($stencil);
				break;
			case 9:
				$data = $this->searchAndAddress($stencil);
				break;
			case 10:
				$data = $this->transverse($stencil);
				break;
			case  11:
				$data = $this->album($stencil);
				break;
		}

		return $data;
	}

	/**
	 * 处理专辑
	 * Created by Jerry
	 * @param array $stencil
	 * @return array|bool
	 */
	protected function album($stencil = array())
	{
		$data = self::$templateModel->find_home_template_album_by_template_id($stencil['id']);

		$albums = $this->getAlbumCover($data);

		if (empty($albums)) {
			$albums = array();
		}

		$albums = self::checkDataSort($albums);

		$stencil['album_list'] = $albums;

		return $stencil;
	}


	/**
	 * Created by Jerry
	 * @param array $albums
	 * @return array|bool
	 */
	protected function getAlbumCover($albums = array())
	{
		if (empty($albums)) {
			return false;
		}

		$albumService = new AlbumService();

		foreach ($albums as $key => $value) {
			$cover = $albumService->getAlbumCover($value['id']);

			if ($cover) {
				$albums[$key]['cover'] = $cover;
			}

		}

		return $albums;
	}

	/**
	 * 地址与搜索模块
	 * Created by Jerry
	 * @param $stencil
	 * @return mixed
	 */
	protected function searchAndAddress($stencil)
	{
		return $stencil;
	}


	/**
	 * Created by Jerry
	 * @param $stencil
	 * @return bool|mixed
	 */
	protected function categoryGoods($stencil)
	{
		if (empty($stencil)) {
			return false;
		}

		$categoryInfo = $this->findCategoryByStencilId($stencil['id']);

		$goods = $this->checkGoodsCategory($categoryInfo);

		if (empty($goods)) {
			$goods = array();
		}

		$stencil['goods_list'] = $goods;
		$stencil['type'] = 4;

		return $stencil;
	}

	/**
	 * Created by Jerry
	 * @param $id
	 * @return bool
	 */
	protected function findCategoryByStencilId($id)
	{
		if (empty($id)) {
			return false;
		}

		return self::$templateStencilGoodsCategoryModel->findCategoryByStencilId($id);
	}

	/**
	 * Created by Jerry
	 * @param $category
	 * @return mixed
	 */
	protected function checkGoodsCategory($category)
	{
		$goods = $this->findCategoryGoodsByCategoryId($category['category_id'], $category['goods_where'], $this->wid);

		$goodsList = self::$goodsRepository->formatGoodsTransform($goods);

		if (count($goodsList) > 1) {
			$goodsList = self::checkDataSort($goodsList);
		}

		$goodsList = array_merge($goodsList);

		return $goodsList;

	}

	/**
	 * Created by Jerry
	 * @param $category_id
	 * @param $goods_where
	 * @param int $wid
	 * @return bool|mixed
	 */
	protected function findCategoryGoodsByCategoryId($category_id, $goods_where, $wid = 8)
	{
		return self::$goodsRepository->findCategoryGoodsByCategoryId($category_id, $goods_where, $wid);
	}

	/**
	 * 为你优选
	 * Created by Jerry
	 * @param $stencil
	 * @return mixed
	 */
	protected function recommend($stencil)
	{
		return $stencil;
	}

	/**
	 * Created by Jerry
	 * @return array|bool
	 */
	public function getBuyNowGroupData()
	{
		$time = gmtime();
		$getTime = date('Y-m-d', $time);
		$startTime = strtotime($getTime) - 28800; //开始时间
		$endTime = strtotime('+1 days', $startTime);  //结束时间

		$data = $this->findGoodsBuyNowListByPromoteTime($startTime, $endTime);

		if (empty($data)) {
			return false;
		}

		$goods = array();
		foreach ($data as $key => $value) {
			$arr = $this->checkBuyNowGoodsDataFormat($value);

			if ($arr['buy_now_status'] == 1) {
				continue;
			}
			$goods[$key] = $arr;
		}

		$groupGoods = self::checkBuyNowGoodsDateGroup($goods);
		$groupGoods = array_merge($groupGoods);

		return $groupGoods;
	}

	/**
	 * 处理秒杀类型
	 * Created by Jerry
	 * @param $stencil
	 * @return mixed
	 */
	protected function buyNowType($stencil)
	{
		$time = gmtime();
		$getTime = date('Y-m-d', $time);
		$startTime = strtotime($getTime) - 28800; //开始时间
		$endTime = strtotime('+1 days', $startTime);  //结束时间

		$data = $this->findGoodsBuyNowListByPromoteTime($startTime, $endTime);

		if (empty($data)) {
			return false;
		}

		$goods = array();
		foreach ($data as $key => $value) {
			$arr = $this->checkBuyNowGoodsDataFormat($value);

			if ($arr['buy_now_status'] == 1) {
				continue;
			}
			$goods[$key] = $arr;
		}

		$groupGoods = self::checkBuyNowGoodsDateGroup($goods);
		$groupGoods = array_merge($groupGoods);

//		$buyNowGoodsList = self::checkDataSort($goods, 'buy_now_status');
		$buyNowGoodsListNow = self::checkDataSortAsc($goods, 'buy_now_end_time', 3);
		$buyNowGoodsListNext = self::checkDataSortAsc($goods, 'buy_now_start_time', 2);
		$buyNowGoodsList = array_merge($buyNowGoodsListNow, $buyNowGoodsListNext);

		$stencil['buy_now_group'] = $groupGoods;
		$stencil['buy_now_list'] = $buyNowGoodsList;
		return $stencil;
	}


	/**
	 * 处理秒杀数据结构
	 * Created by Jerry
	 * @param $goods
	 * @return bool|mixed
	 */
	protected function checkBuyNowGoodsDataFormat($goods)
	{
		if (empty($goods)) {
			return false;
		}
		return self::$buyNowGoodsRepository->formatBuyNowGoodsData($goods);
	}

	/**
	 * 处理秒杀分组数据
	 * Created by Jerry
	 * @param $data
	 * @return array|bool
	 */
	static protected function checkBuyNowGoodsDateGroup($data)
	{
		if (empty($data)) {
			return false;
		}

		$goods = array();
		foreach ($data as $key => $value) {
			$key = $value['buy_now_time_key'];
			$goods[$key]['date_key'] = $value['buy_now_date_key'];
			unset($value['buy_now_date_key'], $value['buy_now_time_key']);
			$goods[$key]['goods_list'][] = $value;
		}

		return $goods;
	}

	/**
	 * Created by Jerry
	 * @param $stencil
	 * @return array|bool
	 */
	protected function seminarType($stencil)
	{
		$stencils = $this->findTemplateStencilSeminarByStencilId($stencil['id']);

		if (empty($stencils)) {
			return false;
		}

		foreach ($stencils as $key => $value) {
			$stencil['size'] = $value['size'];
			$data = $this->findTemplateStencilSeminarForSeminarById($value['seminar_id']);

			if (empty($data)) {
				continue;
			}

			$data['image'] = $this->checkImageUrlReplace($data['image']);

			$data['sort'] = $value['sort'];

			$data = self::checkDataSort($data);

			$stencil['seminar_list'][] = $data;
		}

		if (empty($stencil['seminar_list'])) {
			return false;
		}

		return $stencil;
	}


	/**
	 * Created by Jerry
	 * @param $stencil
	 * @return mixed
	 */
	protected function fontType($stencil)
	{

		$content = $this->findTemplateStencilFontByStencilId($stencil['id']);

		$stencil['content'] = $content['content'];

		if ($content['type'] == 1) {
			$notices = $this->findNotices($stencil['id']);

			if (empty($notices)) {
				$notices = array();
			}

			$stencil['notices_new'] = $notices;

			$result = preg_split('/[;\r\n]+/s', $content['content']);

			if (empty($result)) {
				$result = array();
			}

			$stencil['notices'] = $result;
			unset($stencil['content']);
		}

		$stencil['font_type'] = $content['type'];

		$stencil['font_title'] = $content['title'];
		$stencil['font_small'] = $content['small'];

		$stencil['link'] = $content['link'];

		unset($stencil['orientation']);
		return $stencil;
	}

	/**
	 * Created by Jerry
	 * @param int $id
	 * @return array
	 */
	protected function findNotices($id = 0)
	{
		$notices = self::$templateStencilFontModel->find_template_stencil_font_notice_by_stencil_id($id);

		$data = array();
		if (! empty($notices) && is_array($notices)) {
			foreach ($notices as $key => $value) {
				$data[] = $value;
			}
		}

		return $data;
	}

	/**
	 * Created by Jerry
	 * @param $stencil
	 * @return mixed
	 */
	protected function imageType($stencil)
	{
		$images = $this->findTemplateStencilImageByStencilId($stencil['id']);

		if (count($images) > 1) {
			$images = self::checkDataSort($images);
		}

		$imageSize = array(
			1	=>	'750px 360px',
			2	=>	'710px 360px',
			3	=>	'750px * 260px',
			4	=>	'750px 180px',
			5	=>	'345px 400px',
			6	=>	'365px 175px',
			7	=>	'223px 320px',
		);

		foreach ($images as $key => $value) {

//			if (($value['size'] == 7 || $value['size'] == 5 || $value['size'] == 6) && ($this->is_ios && $this->version <= '2.3.5')) {
//				return false;
//			}

//			修改图片处理地址
			$images[$key]['url'] = $this->checkImageUrlReplace($value['url']);

			if (empty($stencil['size'])) {
				$stencil['size'] = $value['size'];
				$stencil['size_message'] = $imageSize[$stencil['size']];
			}

			unset($images[$key]['size']);
		}

		$images = self::checkDataSort($images);

		$stencil['images_list'] = $images;

		return $stencil;
	}

	/**
	 * oss图片地址转换
	 * Created by Jerry
	 * @param $url
	 * @return mixed
	 */
	protected function checkImageUrlReplace($url)
	{

		$urlPos = strpos($url, '//oss.shidexian.com');
		if ($urlPos !== false) {
			$url = str_replace('//oss.', 'https://image.', $url);
		}

		return $url;
	}

	/**
	 * Created by Jerry
	 * @param $stencil
	 * @return mixed
	 */
	protected function speedType($stencil)
	{
		$images = $this->findTemplateStencilImageByStencilId($stencil['id']);

		if (count($images) > 1) {
			$images = self::checkDataSort($images);
		}

		$imageSize = array(
			1	=>	'750px 360px',
			2	=>	'710px 360px',
			3	=>	'750px * 260px'
		);

		foreach ($images as $key => $value) {

			if (empty($stencil['size'])) {
				$stencil['size'] = $value['size'];
				$stencil['size_message'] = $imageSize[$stencil['size']];
			}

//			处理图片链接地址
			$images[$key]['url'] = $this->checkImageUrlReplace($value['url']);

			unset($images[$key]['size']);
		}

		$stencil['images_list'] = $images;

		return $stencil;
	}

	/**
	 * 四个图片模块
	 * Created by Jerry
	 * @param $stencil
	 * @return mixed
	 */
	protected function transverse($stencil)
	{
		$images = $this->findTemplateStencilImageByStencilId($stencil['id']);

		if (count($images) > 1) {
			$images = self::checkDataSort($images);
		}

		$transverse = array(
			1	=>	'750px 260px',
		);

		foreach ($images as $key => $value) {

			if (empty($stencil['size'])) {
				$stencil['size'] = $value['size'];
				$stencil['size_message'] = $transverse[$stencil['size']];
			}

//			处理图片链接地址
			$images[$key]['url'] = $this->checkImageUrlReplace($value['url']);

			if (!isset($stencil['transverse_image'])) {
				$stencil['transverse_image'] = $value['url'];
			}

			unset($images[$key]['size']);
		}

		$stencil['images_list'] = $images;

		return $stencil;
	}

	/**
	 * 二维数组排序
	 * Created by Jerry
	 * @param $data
	 * @param string $sortKey
	 * @return mixed
	 */
	static protected function checkDataSort($data, $sortKey = 'sort')
	{
		$sort = array();
		foreach ($data as $key => $value) {
			$sort[] = $value[$sortKey];
		}

		array_multisort($sort, SORT_DESC, $data);

		return $data;
	}

	/**
	 * 排序
	 * Created by Jerry
	 * @param $data
	 * @param string $sortKey
	 * @param int $status
	 * @return mixed
	 */
	static protected function checkDataSortAsc($data, $sortKey = 'sort', $status = 3)
	{

		$arr = array();
		$sort = array();
		foreach ($data as $key => $value) {
			if ($value['buy_now_status'] == $status) {
				$arr[] = $value;
				$sort[] = $value[$sortKey];
			}
		}

		array_multisort($sort, SORT_ASC, $arr);

		return $arr;
	}

	/**
	 * 返回商品类型数据
	 * Created by Jerry
	 * @param $stencil
	 * @return mixed
	 */
	protected function goodsType($stencil)
	{
		$goods = $this->findTemplateStencilGoodsByStencilId($stencil['id']);

		if (empty($goods)) {
			return false;
		}

//		商品数据处理
		$goods = self::$goodsRepository->formatGoodsTransform($goods);

		if (count($goods) > 1) {
			$goods = self::checkDataSort($goods);
		}

		if (empty($goods)) {
			$goods = array();
		}

		$goods = array_merge($goods);
		$stencil['goods_list'] = $goods;

		return $stencil;
	}

	/**
	 * Created by Jerry
	 * @param $templateId
	 * @return mixed
	 */
	public function getTemplateStencil($templateId)
	{
		return $this->findTemplateById($templateId);
	}
}